<?php
class Helper_BSS_API
{
	static function pushZencartProductInfo($data, $wn, $api_type, $author)
	{
		set_time_limit(600);
		$service_uri = 'http://api.boxintheship.com/api_select_control_v1.11.9.php?on=' . Q::ini('custom_api/website_api_key') . "&wn={$wn}&apiType={$api_type}&action=product/s_import";
		$pre_data = 'author='. $author .'&key=YIruRgsHO.AzOosg3wFxjxVRq&content=';
		$data = $pre_data.urlencode($data);
		
		$ch = curl_init();
		$timeout = 300;
		curl_setopt($ch, CURLOPT_URL, $service_uri);
		curl_setopt($ch, CURLOPT_POST, true);
//		if (Q::ini('custom_api/proxy_status') == 'On')
//		{
			curl_setopt($ch, CURLOPT_PROXY, Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'));
//		}
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$response = curl_exec($ch);
		curl_close($ch);
	}
	
	static function getZencartCustomerByAPI($shop_id, $sdate, $edate)
	{
		set_time_limit(600);
		$website = Shop_API_Website::find('shop_id=?', $shop_id)
			->joinLeft('shop', 'shop.platform', 'shop.id=shop_api_website.shop_id')
			->asArray()->getOne();
		$api_type = md5($website['platform']);
		if (true)
		{
			$opt = array('http' => array('proxy' => Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'), 'request_fulluri' => true));
			$context = stream_context_create($opt);
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_orders_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=get_customer_info&sdate={$sdate}&edate={$edate}", false, $context);
		}
		else
		{
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_orders_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=get_customer_info&sdate={$sdate}&edate={$edate}");
		}
		if ( ! $remote_data)
		{
			return '';
		}
		return unserialize((base64_decode($remote_data)));
	}
	
	static function getProductImageUrl($number, $isJson=false)
	{
		set_time_limit(300);
		$remote_data = Product_Basic::find('number=?', $number)->asArray()->getOne();
		if($isJson) return json_decode($remote_data['img']);
		return array_filter(explode(";", $remote_data['img']));
	}
	
	static function getZencartOrderByAPI($shop_id, $sdate, $edate)
	{
		set_time_limit(600);
		$website = Shop_API_Website::find('shop_id=?', $shop_id)
			->joinLeft('shop', 'shop.platform', 'shop.id=shop_api_website.shop_id')
			->asArray()->getOne();
		$api_type = md5($website['platform']);
		if (true)
		{
			$opt = array('http' => array('proxy' => Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'), 'request_fulluri' => true));
			$context = stream_context_create($opt);
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_orders_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=sales_order&sdate={$sdate}&edate={$edate}", false, $context);
		}
		else
		{
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_orders_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=sales_order&sdate={$sdate}&edate={$edate}");
		}
		if ( ! $remote_data)
		{
			return '';
		}
		return unserialize((base64_decode($remote_data)));
	}
	
	static function getMagentoOrderByAPI($shop_id, $sdate, $edate)
	{
		set_time_limit(600);
		$website = Shop_API_Website::find('shop_id=?', $shop_id)
			->joinLeft('shop', 'shop.platform', 'shop.id=shop_api_website.shop_id')
			->asArray()->getOne();
		$api_type = md5($website['platform']);
		if (Q::ini('custom_api/proxy_status') == 'On')
		{
			$opt = array('http' => array('proxy' => Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'), 'request_fulluri' => true));
			$context = stream_context_create($opt);
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_orders_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=sales_order&ukey={$website['ukey']}&sdate={$sdate}&edate={$edate}", false, $context);
		}
		else
		{
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_orders_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=sales_order&ukey={$website['ukey']}&sdate={$sdate}&edate={$edate}");
		}
		if ( ! $remote_data)
		{
			return '';
		}
		return unserialize((base64_decode($remote_data)));
	}
	
	static function PushZencartOrderTrackingNumberByAPI($shop_id, $data)
	{
		set_time_limit(600);
		$website = Shop_API_Website::find('shop_id=?', $shop_id)
			->joinLeft('shop', 'shop.platform', 'shop.id=shop_api_website.shop_id')
			->asArray()->getOne();
		$wn = $website['md5'];
		$api_type = md5($website['platform']);
		$service_uri = 'http://api.boxintheship.com/api_select_control_v1.11.9.php?on=' . Q::ini('custom_api/website_api_key') . "&wn={$wn}&apiType={$api_type}&action=change_orderstatus";
		$ch = curl_init();
		$timeout = 300;
		curl_setopt($ch, CURLOPT_URL, $service_uri);
		curl_setopt($ch, CURLOPT_POST, true);
//		if (Q::ini('custom_api/proxy_status') == 'On')
//		{
			curl_setopt($ch, CURLOPT_PROXY, Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'));
//		}
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		$response = curl_exec($ch);
		curl_close($ch);
		return unserialize(base64_decode($response));
	}
	
	static function ebayAPICall($service_uri, $header, $xml, $api_name, $suffix=1, $log='true', $flag='')
	{
		set_time_limit(300);
// 		$result = Ebay_Api_Call_Log::checkAPICallStatus();
// 		if ($result['ack'] == FAILURE)
// 		{
// 			return array('ack' => FAILURE, 'message' => $result['message'], 'data' => '');
// 		}
// 		$init_log = array('api_name' => $api_name);
// 		$log_id = Ebay_Api_Call_Log::initLog($init_log);
// 		$start_execute_microtime = microtime(true);
		$connection = curl_init();
		curl_setopt($connection, CURLOPT_URL, $service_uri);
		curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($connection, CURLOPT_HTTPHEADER, $header);
		curl_setopt($connection, CURLOPT_POST, 1);
		if (Q::ini('custom_api/ebay_proxy_status') == 'On')
		{
			curl_setopt($connection, CURLOPT_PROXY, Q::ini('custom_api/ebay_proxy_host') . ':' . Q::ini('custom_api/ebay_proxy_port'));
		}
		curl_setopt($connection, CURLOPT_POSTFIELDS, $xml);
		curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($connection, CURLOPT_TIMEOUT, 200);
		$response = trim(curl_exec($connection));
		$errno = curl_errno($connection);
		curl_close($connection);
// 		$execute_microtime = sprintf('%.4f', microtime(true) - $start_execute_microtime);
		if ($response)
		{
			$filename = '';
			if ($log)
			{
				$dom = new DomDocument();
		        $dom->loadXML($response);
		        $dom->formatOutput = true;
				$username = CURRENT_USER_NAME ? CURRENT_USER_NAME : 'system';
				$filename = date('Ymd-His', CURRENT_TIMESTAMP) . '-' . $dom->childNodes->item(0)->nodeName . '-' . $username . '-' . $suffix . '-' . Helper_BSS_Normal::generate(5) . '.xml';
				while (file_exists(Q::ini('custom_system/ebay_api_call_log_dir') . $filename))
				{
					$filename = date('Ymd-His', CURRENT_TIMESTAMP) . '-' . $dom->childNodes->item(0)->nodeName . '-' . $username . '-' . $suffix . '-' . Helper_BSS_Normal::generate(5) . '.xml';
				}
				file_put_contents(Q::ini('custom_system/ebay_api_call_log_dir') . $filename, $dom->saveXML());
			}
			$response_xml = simplexml_load_string($response);
			$message = '';
			if (isset($response_xml->Errors[0]))
			{
				foreach ($response_xml->Errors as $e)
				{
					$message .= (string)$e->LongMessage[0] . "\n";
				}
			}
			elseif (isset($response_xml->errorMessage[0]->error[0]))
			{
				foreach ($response_xml->errorMessage[0]->error as $e)
				{
					$message .= (string)$e->message[0] . "\n";
				}
			}
			$message = rtrim($message, "\n");
// 			$completed_log = array(
// 				'id' => $log_id['id'],
// 				'status' => Q::ini('custom_flag/ebay_api_call_log_status/completed/value'),
// 				'execute_microtime' => $execute_microtime,
// 				'ack' => isset($response_xml->Ack) ? $response_xml->Ack : (isset($response_xml->ack) ? $response_xml->ack : ''),
// 				'message' => $message,
// 				'filename' => $filename,
// 				'other_flag' => $flag,
// 				'errno' => $errno
// 			);
// 			Ebay_Api_Call_Log::completedLog($completed_log);
			return array('ack' => SUCCESS, 'message' => '', 'data' => $response, 'filename' => $filename);
		}
		else
		{
// 			QDB::getConn()->execute('update ebay_api_call_log set status=\'' . Q::ini('custom_flag/ebay_api_call_log_status/completed/value') . '\', execute_microtime=\'' . $execute_microtime . '\', errno=\'' . intval($errno) . '\' where id=\'' . $log_id['id'] . '\'');
			return array('ack' => FAILURE, 'message' => 'API请求返回结果异常，请稍后再试！', 'data' => '');
		}
	}
	
	static function getZencartCategories($shop)
	{
		set_time_limit(600);
		$website = Shop_API_Website::find('shop_id=?', $shop['id'])
			->joinLeft('shop', 'shop.platform', 'shop.id=shop_api_website.shop_id')
			->asArray()->getOne();
		$api_type = md5($website['platform']);
		if (true)
		{
			$opt = array('http' => array('proxy' => Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'), 'request_fulluri' => true));
			$context = stream_context_create($opt);
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_categories_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=categories_tree", false, $context);
		}
		else
		{
			$remote_data = file_get_contents(Q::ini('custom_api/get_zencart_categories_api') . 'on=' . Q::ini('custom_api/website_api_key') . "&wn={$website['md5']}&apiType={$api_type}&action=categories_tree");
		}
		if ($remote_data)
		{
			file_put_contents(Q::ini('custom_system/zencart_categories_dir') . "website{$website['shop_id']}", $remote_data);
		}
		else
		{
			file_put_contents(Q::ini('custom_system/zencart_categories_dir') . "website{$website['shop_id']}", serialize(array()));
		}
	}
	
	static function getshopAnalyserData($shop_md5, $btime, $etime)
	{
		$remote_data = file_get_contents(Q::ini('custom_api/get_shop_analyser_data_api') . "website_md5={$shop_md5}&btime={$btime}&etime={$etime}");
		return unserialize($remote_data);
	}
	
	static function requestItemByNextToken($next_token, $service, $merchant_id)
	{
		$result = array('item' => array(), 'next_token' => '', 'shipping_fee' => 0, 'discount' => 0);
		$next_item_request = new MarketplaceWebServiceOrders_Model_ListOrderItemsByNextTokenRequest();
		$next_item_request->setSellerId($merchant_id);
		$next_item_request->setNextToken($next_token);
		$next_item_response = $service->listOrderItemsByNextToken($next_item_request);
		$listOrderItemsByNextTokenResult = $next_item_response->getListOrderItemsByNextTokenResult();
		if ($listOrderItemsByNextTokenResult->isSetNextToken())
		{
			$result['next_token'] = $listOrderItemsByNextTokenResult->getNextToken();
		}
		if ($listOrderItemsByNextTokenResult->isSetOrderItems())	
		{
			$orderItems = $listOrderItemsByNextTokenResult->getOrderItems();
			$next_result = Helper_BSS_Normal::assembledAmazonItemsToArray($orderItems);
			$result['item'] = $next_result['item'];
			$result['shipping_fee'] = $next_result['shipping_fee'];
			$result['discount'] = $next_result['discount'];
		}
		return $result;
	}
	
	static function requestItemByAmazonAPI($amazon_order_id, $shop_id)
	{
		set_time_limit(0);
		$amazon_shop = Shop_API_Amazon::find('shop_id=?', $shop_id)
				->joinLeft('shop', 'name', 'shop.id=shop_api_amazon.shop_id')
				->asArray()->getOne();
		$service_url = 'https://' . $amazon_shop['mws_endpoint'] . '/Orders/' . Q::ini('custom_api/amazon_mws_services_order_version');
		$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 10,
		);
		$service = new MarketplaceWebServiceOrders_Client(
				$amazon_shop['access_key'],
				$amazon_shop['secret_key'],
				$amazon_shop['application_name'],
				$amazon_shop['version'],
				$config
		);
		$result['item'] = array();
		$item_request = new MarketplaceWebServiceOrders_Model_ListOrderItemsRequest();
		$item_request->setSellerId($amazon_shop['merchant_id']);
		$item_request->setAmazonOrderId($amazon_order_id);
		$item_response = $service->listOrderItems($item_request);
		$listOrderItemsResult = $item_response->getListOrderItemsResult();
		if ($listOrderItemsResult->isSetOrderItems())
		{
			$orderItems = $listOrderItemsResult->getOrderItems();
			$result = Helper_BSS_Normal::assembledAmazonItemsToArray($orderItems);
		}
		if ($listOrderItemsResult->isSetNextToken())
		{
			$next_token = $listOrderItemsResult->getNextToken();
			while ($next_token)
			{
				$next_result = Helper_BSS_API::requestItemByNextToken($next_token, $service, $amazon_shop['merchant_id']);
				$next_token = $next_result['next_token'];
				$result['item'] = array_merge($result['item'], $next_result['item']);
				$result['shipping_fee'] += $next_result['shipping_fee'];
				$result['discount'] += $next_result['discount'];
			}
		}
		return $result;
	}
	
	static function requestListOrdersByNextToken($next_token, $shop_id)
	{
		set_time_limit(0);
		require_once (Q::ini('custom_system/lib_dir') . 'MarketplaceWebServiceOrders/Client.php');
		$amazon_shop = Shop_API_Amazon::find('shop_id=?', $shop_id)
			->joinLeft('shop', 'name', 'shop.id=shop_api_amazon.shop_id')
			->asArray()->getOne();
		$service_url = 'https://' . $amazon_shop['mws_endpoint'] . '/Orders/' . Q::ini('custom_api/amazon_mws_services_order_version');
		$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
		);
		$service = new MarketplaceWebServiceOrders_Client(
			$amazon_shop['access_key'],
			$amazon_shop['secret_key'],
			$amazon_shop['application_name'],
			$amazon_shop['version'],
			$config
		);
		$request = new MarketplaceWebServiceOrders_Model_ListOrdersByNextTokenRequest();
		$request->setNextToken($next_token);
 		$request->setSellerId($amazon_shop['merchant_id']);
 		$response = $service->listOrdersByNextToken($request);
		$listOrdersByNextTokenResult = $response->getListOrdersByNextTokenResult();
		if ($listOrdersByNextTokenResult->isSetOrders())
		{
			$orders = $listOrdersByNextTokenResult->getOrders();
			$sales_order = Helper_BSS_Normal::assembledAmazonOrdersToArray($orders, $shop_id);
			if ($listOrdersByNextTokenResult->isSetNextToken())
			{
				$exists_next_token = $listOrdersByNextTokenResult->getNextToken();
				return array('orders' => $sales_order, 'next_token' => $exists_next_token);
			}
			else
			{
				return array('orders' => $sales_order, 'next_token' => '');
			}
		}
	}
	
	static function getAmazonReportRequestId($shop_ids)
	{
		set_time_limit(0);
		$amazon_shops = Shop_API_Amazon::find('shop_id in (' . implode(',', $shop_ids) . ')')->asArray()->getAll();
		foreach ($amazon_shops as $amazon_shop)
		{
			$service_url = 'https://' . $amazon_shop['mws_endpoint'];
			$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
			);
			$service = new MarketplaceWebService_Client(
				$amazon_shop['access_key'],
				$amazon_shop['secret_key'],
				$config,
				$amazon_shop['application_name'],
				$amazon_shop['version']
			);
			$request_id = '';
			try
			{
				$request = new MarketplaceWebService_Model_RequestReportRequest();
				$request->setMarketplaceIdList(array('Id' => array($amazon_shop['marketplace_id'])));
				$request->setMerchant($amazon_shop['merchant_id']);
				$request->setReportType('_GET_FLAT_FILE_OPEN_LISTINGS_DATA_');
				$response = $service->requestReport($request);
				if ($response->isSetRequestReportResult() && $response->getRequestReportResult()->isSetReportRequestInfo())
				{
					$reportRequestInfo = $response->getRequestReportResult()->getReportRequestInfo();
					if ($reportRequestInfo->isSetReportRequestId())
					{
						$request_id = $reportRequestInfo->getReportRequestId();
						QDB::getConn()->execute('insert into online_amazon_task (shop_id, request_id, request_time) values (' . $amazon_shop['shop_id'] . ', \'' . $request_id . '\', \'' . CURRENT_DATETIME . '\')');
					}
	        	}
			}
			catch (MarketplaceWebService_Exception $ex)
			{
				QDB::getConn()->execute('insert into online_amazon_task (shop_id, request_time, notes) values (' . $amazon_shop['shop_id'] . ', \'' . CURRENT_DATETIME . '\'' . ', \'' . $ex->getMessage() . '\')');
			}
			
		}
		return array('ack' => SUCCESS, 'message' => 'success getAmazonReportRequestId, execute time:' . sprintf('%.4f', microtime(true) - $GLOBALS['g_boot_time']) . '(secs)');
	}
	
	static function getAmazonFeedSumissionResult($shop_id, $id)
	{
		$amazon_shop = Shop_API_Amazon::find('shop_id=?', $shop_id)->asArray()->getOne();
		$service_url = 'https://' . $amazon_shop['mws_endpoint'];
		$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
		);
		$service = new MarketplaceWebService_Client(
				$amazon_shop['access_key'],
				$amazon_shop['secret_key'],
				$config,
				$amazon_shop['application_name'],
				$amazon_shop['version']
		);
		$filename = Q::ini('custom_system/amazon_submit_feed_log_dir'). CURRENT_TIMESTAMP . '-' . $id . '-' . CURRENT_USER_NAME . '.xml';
		$handle = fopen($filename, 'w+');
		$parameters = array (
			'Merchant' => $amazon_shop['merchant_id'],
			'FeedSubmissionId' => $id,
			'FeedSubmissionResult' => $handle,
		);
		$request = new MarketplaceWebService_Model_GetFeedSubmissionResultRequest($parameters);
		try
		{
			$response = $service->getFeedSubmissionResult($request);
		}
		catch (MarketplaceWebService_Exception $ex)
		{
	         echo("Caught Exception: " . $ex->getMessage() . "\n");
	         echo("Response Status Code: " . $ex->getStatusCode() . "\n");
	         echo("Error Code: " . $ex->getErrorCode() . "\n");
	         echo("Error Type: " . $ex->getErrorType() . "\n");
	         echo("Request ID: " . $ex->getRequestId() . "\n");
		}
		if (file_exists($filename))
		{
			dump(simplexml_load_file($filename));
		}
		exit;
	}
	
	static function getAmazonReportListId($amazon_shops)
	{
		set_time_limit(0);
		$wrong_listing = '';
		foreach ($amazon_shops as $amazon_shop)		
		{
			$service_url = 'https://' . $amazon_shop['mws_endpoint'];
			$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
			);
			$service = new MarketplaceWebService_Client(
				$amazon_shop['access_key'],
				$amazon_shop['secret_key'],
				$config,
				$amazon_shop['application_name'],
				$amazon_shop['version']
			);
			try
			{
				$request_list = new MarketplaceWebService_Model_GetReportListRequest();
				$request_list->setMerchant($amazon_shop['merchant_id']);
				$request_list->setMarketplace($amazon_shop['marketplace_id']);
				$request_list->setReportRequestIdList(array($amazon_shop['request_id']));
				$response_list = $service->getReportList($request_list);
				$getReportListResult = $response_list->getGetReportListResult()->getReportInfoList();
				if ($getReportListResult && $getReportListResult[0]->isSetReportId())
				{
					$report_id = $getReportListResult[0]->getReportId();
					$request_report = new MarketplaceWebService_Model_GetReportRequest();
					$request_report->setMerchant($amazon_shop['merchant_id']);
					$request_report->setMarketplace($amazon_shop['marketplace_id']);
					$request_report->setReport(@fopen('php://temp', 'rw+'));
					$request_report->setReportId($report_id);
					$response_report = $service->getReport($request_report);
					$i = 1;
					$products = array();
					while (($buffer = fgets($request_report->getReport(), 10240)) !== false)
					{
					 	if ($i != 1)
					 	{
					 		if ($data = explode("\t", $buffer))
					 		{
						 		$products[] = array('sku' => trim($data[0]), 'price' => str_replace(',', '.', trim($data[2])), 'quantity' => trim($data[3]), 'shop_item_id' => trim($data[1]));
					 		}
					 	}
					 	$i++;
				    }
				    fclose($request_report->getReport());
	        		foreach ($products as $p)
			    	{
			    		if (! Online_Amazon_Product::judgeOnlineAmazonProductFormat($p['sku']))
			    		{
			    			$wrong_listing .= $p['sku'] . "\t" . $p['shop_item_id'] . "\t" . $amazon_shop['name'] . "\t\n";
			    			continue;
			    		}
			    		$old_product = Online_Amazon_Product::find('sku=? and shop_id=?', $p['sku'], $amazon_shop['shop_id'])->getOne();
			    		$status = ($p['quantity'] == 0) ? Q::ini('custom_flag/online_amazon_product_status/offsale/value') : Q::ini('custom_flag/online_amazon_product_status/onsale/value');
			    		if ($old_product['id'])
			    		{
			    			$old_product->shop_item_id = $p['shop_item_id'];
				    		$old_product->price = $p['price'];
				    		$old_product->quantity = $p['quantity'];
				    		$old_product->update_time = CURRENT_DATETIME;
				    		$old_product->status = $status;
				    		$old_product->save();
			    		}
			    		else
			    		{
				    		$product_basic = Product_Basic::find('number=?', substr($p['sku'], 0, 7))->asArray()->getOne();
			    			$product_bind = Product_Bind::find('number=?', substr($p['sku'], 0, 7))->asArray()->getOne();
			    			$online_amazon_product = new Online_Amazon_Product();
				    		$online_amazon_product->shop_id = $amazon_shop['shop_id'];
				    		$online_amazon_product->sku = $p['sku'];
				    		$online_amazon_product->shop_item_id = $p['shop_item_id'];
				    		$online_amazon_product->status = $status;
				    		$online_amazon_product->price = $p['price'];
				    		$online_amazon_product->quantity = $p['quantity'];
				    		$online_amazon_product->update_time = CURRENT_DATETIME;
			    			if ($product_basic)
			    			{
			    				$online_amazon_product->product_basic_id = $product_basic['id'];
			    				$online_amazon_product->open_time = $product_basic['create_time'];
			    			}
			    			if ($product_bind)
			    			{
			    				$online_amazon_product->open_time = $product_bind['create_time'];
			    			}
				    		$online_amazon_product->save();
			    		}
			    	}
			    	QDB::getConn()->execute('update online_amazon_task set report_id=' . $report_id . ', report_time=\'' . CURRENT_DATETIME . '\' where id=' . $amazon_shop['online_amazon_task_id']);
				}
				else
				{
					QDB::getConn()->execute('update online_amazon_task set notes=\'Request Report List ID is NULL\' where id=' . $amazon_shop['online_amazon_task_id']);
				}
			}
			catch (MarketplaceWebService_Exception $ex)
			{
		        QDB::getConn()->execute('update online_amazon_task set notes=\'' . $ex->getMessage() . '\' where id=' . $amazon_shop['online_amazon_task_id']);
			}
		}
		if ($wrong_listing)
    	{
    		$wrong_listing = "错误SKU\t店铺ID\t所在店铺\t\n" . $wrong_listing;
    		$wrong_listing = iconv("UTF-8","UTF-16LE",$wrong_listing);
			$wrong_listing = "\xFF\xFE".$wrong_listing;
			$file_name = date('Y-m-d', CURRENT_TIMESTAMP) . '-' . "Amazon.xls";
			$file = file_put_contents(Q::ini('custom_system/wrong_listing_dir') . $file_name, $wrong_listing);
    	}
		return array('ack' => SUCCESS, 'message' => 'success getAmazonReportListId, execute time:' . sprintf('%.4f', microtime(true) - $GLOBALS['g_boot_time']) . '(secs)');
	}
	
	static function iEUBAPICall($service_uri, $type, $xml = '', $log='true')
	{
		$header = array(
			'version:' . Q::ini('custom_api/ieub_api_version'),
			'authenticate:' . Q::ini('custom_api/ieub_api_authenticate')
		);
		$connection = curl_init();
		curl_setopt($connection, CURLOPT_URL, $service_uri);
		curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($connection, CURLOPT_HTTPHEADER, $header);
		curl_setopt($connection, CURLOPT_CUSTOMREQUEST, $type);
		curl_setopt($connection, CURLOPT_TIMEOUT, 200);
		if ($type == 'POST')
		{
			curl_setopt($connection, CURLOPT_POSTFIELDS, $xml);
		}
		curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
		if (Q::ini('custom_api/proxy_status') == 'On')
		{
			curl_setopt($connection, CURLOPT_PROXY, Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'));
		}
		$response = trim(curl_exec($connection));
		if ($log && $response)
		{
			$username = CURRENT_USER_NAME ? CURRENT_USER_NAME : 'system';
			$filename = Q::ini('custom_system/ieub_api_call_log_dir') . date('Ymd-His', CURRENT_TIMESTAMP) . '-' . $username . '.xml';
			file_put_contents($filename, $response);
		}
		return $response;
	}
	
	static function ebayTemplateRsync()
	{
		$cmd = 'rsync -vzrtopg --progress --delete ' . Q::ini('custom_system/ebay_template_prodcution_for_outside_dir') . ' ebtpl@ebtpl.xftl.com::ebtpl --password-file=' . Q::ini('custom_system/ebay_template_rsync_password_file');
		exec($cmd);
	}
	
	static function AliSignature($param, $secret)
	{
		ksort($param);
		$sign = '';
		foreach ($param as $key => $val)
		{
			if ($key != '' && $val != '')
			{
				$sign .= $key . $val;
			}
		}
		$sign = strtoupper(bin2hex(hash_hmac("sha1", $sign, $secret, true)));
		return $sign;
	}
	
	static function AliExpressAPICall($service_uri, $param, $need_sign = false, $secret = '', $type='POST')
	{
		if ($need_sign)
		{
			$sign = Helper_BSS_API::AliSignature($param, $secret);
			$param['_aop_signature'] = $sign;
		}
		if ($type == 'GET')
		{
			$service_uri .= '?' . http_build_query($param);
		}
		$connection = curl_init();
		curl_setopt($connection, CURLOPT_URL, $service_uri);
		curl_setopt($connection, CURLOPT_CUSTOMREQUEST, $type);
		curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
		if ($type == 'POST')
		{
			curl_setopt($connection, CURLOPT_POSTFIELDS, http_build_query($param));
		}
		curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, false);
		if (Q::ini('custom_api/proxy_status') == 'On')
		{
			curl_setopt($connection, CURLOPT_PROXY, Q::ini('custom_api/proxy_host') . ':' . Q::ini('custom_api/proxy_port'));
		}
		$result = curl_exec($connection);
		curl_close($connection);
		$ret = json_decode($result, true);
		return $ret;
	}
	
	static function AutoImportAmazonOrder($shop, $begin_sales_time, $end_sales_time)
	{
		set_time_limit(0);
		$message = '';
		foreach ($shop as $s)
		{
			$service_url = 'https://' . $s['mws_endpoint'] . '/Orders/' . Q::ini('custom_api/amazon_mws_services_order_version');
			$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $s['proxy_host'] ? $s['proxy_host'] : null,
				'ProxyPort' => $s['proxy_port'] ? $s['proxy_port'] : -1,
				'MaxErrorRetry' => 5,
			);
			$service = new MarketplaceWebServiceOrders_Client(
				$s['access_key'],
				$s['secret_key'],
				$s['application_name'],
				$s['version'],
				$config
			);
			$sales_order = array();
			$channels_status = array('AFN' => array('Shipped'), 'MFN' => array('Unshipped', 'PartiallyShipped'));
			foreach ($channels_status as $k => $cs)
			{
				$request = new MarketplaceWebServiceOrders_Model_ListOrdersRequest();
				$request->setSellerId($s['merchant_id']);
				$request->setMarketplaceId($s['marketplace_id']);
				$request->setOrderStatus($cs);
				$start_time = explode(' ', $begin_sales_time);
				$end_time = explode(' ', $end_sales_time);
				$LastUpdateAfter = isset($start_time[1]) ? $begin_sales_time : $begin_sales_time . '00:00:00';
				$LastUpdateBefore = isset($end_time[1]) ? (($end_sales_time >= date('Y-m-d H:i', CURRENT_TIMESTAMP)) ? date('Y-m-d H:i:s', CURRENT_TIMESTAMP-600) : $end_sales_time) :  $end_sales_time . ' 23:59:59';
				$request->setLastUpdatedAfter(date('c', strtotime($LastUpdateAfter)));
				$request->setLastUpdatedBefore(date('c', strtotime($LastUpdateBefore)));
				$request->setFulfillmentChannel($k);
				try
				{
					$response = $service->listOrders($request);
					$listOrdersResult = $response->getListOrdersResult();
					if ($listOrdersResult)
					{
						if ($listOrdersResult->isSetOrders())
						{
							$orders = $listOrdersResult->getOrders();
							$sales_order = array_merge($sales_order, Helper_BSS_Normal::assembledAmazonOrdersToArray($orders, $s['shop_id']));
							foreach ($sales_order as $k => $so)
							{
								$check_exists = Sales_Order::judgeImport($s['shop_id'], $so['shop_order_number']);
								$sales_order[$k]['item'] = array();
								if ($check_exists['ack'] == SUCCESS)
								{
									$item_result = Helper_BSS_API::requestItemByAmazonAPI($so['shop_order_number'], $s['shop_id']);
									$sales_order[$k]['item'] = $item_result['item'];
									$sales_order[$k]['shipping_fee'] = $item_result['shipping_fee'];
									$sales_order[$k]['discount'] = $item_result['discount'];
								}
							}
							$sales_order_result = Sales_Order::import($sales_order);
							if ($sales_order_result['ack'] != SUCCESS)
							{
								$message .= $sales_order_result['message'];
							}
						}
						if ($listOrdersResult->isSetNextToken()) 
						{
							$next_token = $listOrdersResult->getNextToken();
							while ($next_token)
							{
								$result = Helper_BSS_API::requestListOrdersByNextToken($next_token, $s['shop_id']);
								$next_token = $result['next_token'];
								if (! empty($result['orders']))
								{
									foreach ($result['orders'] as $k => $so)
									{
										$check_exists = Sales_Order::judgeImport($s['shop_id'], $so['shop_order_number']);
										$result['orders'][$k]['item'] = array();
										if ($check_exists['ack'] == SUCCESS)
										{
											$item_result = Helper_BSS_API::requestItemByAmazonAPI($so['shop_order_number'], $s['shop_id']);
											$result['orders'][$k]['item'] = $item_result['item'];
											$result['orders'][$k]['shipping_fee'] = $item_result['shipping_fee'];
											$result['orders'][$k]['discount'] = $item_result['discount'];
										}
									}
									$sales_order_result = Sales_Order::import($result['orders']);
									if ($sales_order_result['ack'] != SUCCESS)
									{
										$message .= $sales_order_result['message'];
									}
								}
							}
						}
					}
				}
				catch (MarketplaceWebServiceOrders_Exception $ex)
				{
					echo("Caught Exception: " . $ex->getMessage() . "\n");
			        echo("Response Status Code: " . $ex->getStatusCode() . "\n");
			        echo("Error Code: " . $ex->getErrorCode() . "\n");
			        echo("Error Type: " . $ex->getErrorType() . "\n");
			        echo("Request ID: " . $ex->getRequestId() . "\n");
			        echo("XML: " . $ex->getXML() . "\n");
			        echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
					continue;
				}
			}
		}
		return array('ack' => SUCCESS, 'message' => $message);
	}
	
	/**
	 * Amazon上传数据API整合方法
	 * @param 店铺ID $shop_id
	 * @param 上传数据 $xml
	 * @param 枚举上传数据类型 $feed_type
	 */
	static function submitFeedToAmazon($shop_id, $xml, $feed_type)
	{
		$amazon_shop = Shop_API_Amazon::find('shop_id=?', $shop_id)->asArray()->getOne();
		$service_url = 'https://' . $amazon_shop['mws_endpoint'];
		$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
		);
		$service = new MarketplaceWebService_Client(
				$amazon_shop['access_key'],
				$amazon_shop['secret_key'],
				$config,
				$amazon_shop['application_name'],
				$amazon_shop['version']
		);
		$feedHandle = @fopen('php://temp', 'rw+');
		fwrite($feedHandle, $xml);
		rewind($feedHandle);
		$parameters = array (
		  'Merchant' => $amazon_shop['merchant_id'],
		  'MarketplaceIdList' => array("Id" => array($amazon_shop['marketplace_id'])),
		  'FeedType' => $feed_type,
		  'FeedContent' => $feedHandle,
		  'PurgeAndReplace' => false,
		  'ContentMd5' => base64_encode(md5(stream_get_contents($feedHandle), true)),
		);
		rewind($feedHandle);
		$request = new MarketplaceWebService_Model_SubmitFeedRequest($parameters);
		$response = $service->submitFeed($request);
		if ($response->isSetSubmitFeedResult())
		{
			$feedSubmissionInfo = $response->getSubmitFeedResult()->getFeedSubmissionInfo();
			$feedSubmissionId = $feedSubmissionInfo->getFeedSubmissionId();
			file_put_contents(Q::ini('custom_system/amazon_submit_feed_log_dir') . date('Ymd-His', CURRENT_TIMESTAMP) . '-' . $feedSubmissionId . '-' . CURRENT_USER_NAME . '.xml', $xml);
		}
		@fclose($feedHandle);
		if (isset($feedSubmissionId))
		{
			return array('ack' => SUCCESS, 'message' => '', 'data' => $feedSubmissionId);
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '上传失败，没有获取到上传ID！');
		}
	}
	
	/**
	 * pms图片管理系统 API 调用
	 * @param $action_type API动作名称
	 * @param $param_data API参数
	 */
	static function PMSCall($action_type, $param_data=null)
	{
		// 请求参数 encode 
		$encode_param_data = base64_encode(gzcompress(json_encode($param_data),9));
		$encode_param_data = str_replace(array('+','/','='), array('-','_',''), $encode_param_data);
		
		$ch = curl_init("http://pms.boxintheship.com:9011/api.php?action={$action_type}&data={$encode_param_data}");
		curl_setopt($ch, CURLOPT_BINARYTRANSFER,  true);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$encode_return = curl_exec($ch);
		curl_close($ch);
		// 返回结果 decode
		$decode_return = str_replace(array('-','_'),array('+','/'), $encode_return);
		$decode_return = json_decode(gzuncompress(base64_decode($decode_return)),true);
		
		return ($decode_return);
	}
	
	static function wishAPICall($uri, $timeout = 300)
	{
		$response = array();
		do
		{
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $uri);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
			$output = curl_exec($ch);
			curl_close($ch);
			$output = json_decode($output, true);
			foreach($output['data'] as $o)
			{
				$response[] = $o['order'];
			}
			if (isset($output['paging']['next']) && $output['paging']['next'])
			{
				$uri = $output['paging']['next'];
			}
		} while (isset($output['paging']['next']));
		if ($response)
		{
			return array('ack' => SUCCESS, 'message' => '', 'data' => $response);
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'API请求返回结果异常，请稍后再试！', 'data' => '');
		}
	}
	
	/**
	 * wintAPI生成令牌
	 * @param $action API动作名称
	 * @param $data API提交数据
	 */
	static function winitSign($data, $action)
	{
		$token_data = array(
	        'action' => $action,
			'app_key' => Q::ini('custom_api/Winit_api_uname'),
			'data' => $data,
			'format' => Q::ini('custom_api/Winit_api_format'),
			'platform' => Q::ini('custom_api/Winit_api_platform'),
			'sign_method' => Q::ini('custom_api/Winit_api_sign_method'),
			'timestamp' => date('Y-m-d H:i:s'),
			'version' => Q::ini('custom_api/Winit_api_version')
		);
		$sign_string = '';
		foreach ($token_data as $k => $td)
		{
			if(is_array($td))
			{
				$sign_string .= $k . json_encode($td, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
			}
			else
			{
				$sign_string .= $k . $td;
			}
		}
		$sign_string = Q::ini('custom_api/Winit_api_token') . $sign_string . Q::ini('custom_api/Winit_api_token');
		$sign_string = strtoupper(md5($sign_string));
		$sign = array(
			'sign' => $sign_string,
			'language' => Q::ini('custom_api/Winit_api_language')
		);
		$data = array_merge($token_data, $sign);
		$return_json = json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
		return $return_json;
	}
	
	/**
	 * 提交winitAPI请求数据
	 * @param $data API提交数据(json)
	 * @param $url API请求地址
	 */
	static function winitAPICall($data, $url)
	{
		try
		{
			$connection = curl_init();
			curl_setopt($connection, CURLOPT_URL, $url);
			curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
			curl_setopt($connection, CURLOPT_HTTPHEADER, array('Content-Type: text/xml;charset=utf-8'));
			curl_setopt($connection, CURLOPT_POST, 1);
			curl_setopt($connection, CURLOPT_POSTFIELDS, $data);
			curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
			$response = curl_exec($connection);
			curl_close($connection);
			if($response === false)
			{
				$error = '服务器连接失败，请检查网络是否正常！';
				return array('ack' => FAILURE, 'message' => $error, 'data' => '');
			}
			else
			{
				$ret = json_decode($response, true);
				if ($ret['code'] == 0)
				{
					return array('ack' => SUCCESS, 'message' => $ret['msg'], 'data' => $ret['data']);
				}
				else
				{
					return array('ack' => FAILURE, 'message' => $ret['msg'], 'data' => $ret['code']);
				}
			}
		}
		catch (Exception $e)
		{
			$error = '服务器连接失败，请检查网络是否正常！';
			return array('ack' => FAILURE, 'message' => $error, 'data' => '');
		}
	}
}
